import { Form, Input, Button, Select, Card, message, Modal } from "antd";
import { EyeOutlined } from "@ant-design/icons";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import MDEditor from "@uiw/react-md-editor";
import service from "@/http/request";

const { Option } = Select;

const sectionMap = {
  图书: "BOOK",
  交友: "SOCIAL",
  软件: "SOFTWARE",
  音乐: "MUSIC",
  影视: "MOVIE",
};

const PostForm = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [markdown, setMarkdown] = useState("");
  const [previewVisible, setPreviewVisible] = useState(false);

  const handleSubmit = async (values) => {
    const postData = {
      title: values.title,
      content: markdown,
    };
    console.log(postData);
    try {
      const section = sectionMap[values.category];
      await service.post(`/forum2/sections/${section}/posts`, postData);
      message.success("帖子发布成功！");
      navigate("/forum");
    } catch (error) {
      console.error("发布失败：", error);
      message.error("帖子发布失败，请稍后重试");
    }
  };

  const handlePreview = async () => {
    try {
      await form.validateFields();
      setPreviewVisible(true);
    } catch {
      message.warning("请先填写完整标题、分类和内容！");
    }
  };

  return (
    <div style={{ maxWidth: 800, margin: "40px auto" }}>
      <Card
        title="📝 发布新帖子"
        bordered={false}
        style={{
          boxShadow: "0 2px 10px rgba(0, 0, 0, 0.05)",
          borderRadius: 10,
        }}
      >
        <Form
          layout="vertical"
          form={form}
          onFinish={handleSubmit}
          initialValues={{ category: "图书" }}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: "请输入帖子标题" }]}
          >
            <Input placeholder="请输入标题" />
          </Form.Item>

          <Form.Item label="内容（支持 Markdown 格式）" required>
            <div
              data-color-mode="light"
              style={{ border: "1px solid #d9d9d9", borderRadius: 6 }}
            >
              <MDEditor value={markdown} onChange={setMarkdown} height={300} />
            </div>
          </Form.Item>

          <Form.Item
            label="分类模块"
            name="category"
            rules={[{ required: true, message: "请选择模块" }]}
          >
            <Select>
              {["图书", "交友", "软件", "音乐", "影视"].map((mod) => (
                <Option key={mod} value={mod}>
                  {mod}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            style={{ display: "flex", gap: 10, justifyContent: "center" }}
          >
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginRight: "100px" }}
            >
              发布帖子
            </Button>
            <Button icon={<EyeOutlined />} onClick={handlePreview}>
              预览帖子
            </Button>
          </Form.Item>
        </Form>
      </Card>

      {/* 帖子预览 */}
      <Modal
        title="帖子预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width={800}
      >
        <h2>{form.getFieldValue("title")}</h2>
        <MDEditor.Markdown
          source={markdown || "*暂无内容*"}
          style={{ background: "#f9f9f9", padding: 16 }}
        />
      </Modal>
    </div>
  );
};

export default PostForm;
